package com.ynu.springbootappdemo.service;

import com.ynu.springbootappdemo.common.exception.BusinessException;
import com.ynu.springbootappdemo.common.service.LogicService;
import com.ynu.springbootappdemo.common.utils.ErrorCode;
import com.ynu.springbootappdemo.dao.ICityDao;
import com.ynu.springbootappdemo.dao.IFoodDao;
import com.ynu.springbootappdemo.model.dto.food.FoodAddRequest;
import com.ynu.springbootappdemo.model.entity.City;
import com.ynu.springbootappdemo.model.entity.Food;
import com.ynu.springbootappdemo.model.vo.FoodVo;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class FoodService extends LogicService<IFoodDao, Food,Long> {
    public FoodService(@Autowired IFoodDao dao) {
        super(dao);
    }

    @Resource
    private ICityDao cityDao;
    @Resource
    private ModelMapper modelMapper;

    @Resource
    private UploadService uploadService;

    /**
     * 根据城市获取食物
     *  @param cityId
     *  @return
     * */
    public List<FoodVo> getFoodsByCityId(Long cityId){
        City city = cityDao.getReferenceById(cityId);
        return dao.findFoodsByCity(city).stream().map(
                food -> modelMapper.map(food, FoodVo.class)).collect(Collectors.toList());
    }

    /**
     * 获取除某个食物之外的城市食物
     *  @param cityId
     *  @param foodId
     * */
    public List<FoodVo> getFoodsByCityIdExceptFoodId(Long cityId,Long foodId){
        City city = cityDao.getReferenceById(cityId);
        return dao.findFoodsByIdIsNotAndCity(foodId,city).stream().map(
                food -> modelMapper.map(food, FoodVo.class)).collect(Collectors.toList());
    }

    /**
     * 添加食物
     *   @param foodAddRequest
     *   @return
     * */
    public FoodVo add(FoodAddRequest foodAddRequest){
        try {
            Food food = modelMapper.map(foodAddRequest, Food.class);
            //获取城市
            City city = cityDao.findCityByCityName(foodAddRequest.getCityName());
            if (Objects.isNull(city)){
                throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
            }
            food.setCity(city);
            String uploadFile = uploadService.uploadFile(foodAddRequest, foodAddRequest.getCityName());
            food.setImageUrl(uploadFile);
            return modelMapper.map(dao.save(food), FoodVo.class);
        }catch (Exception e){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
    }

}
